const formatTime = (date, showhour = false, isdate = true, showH_S = false) => {
  if (isdate) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    if (showhour) {
      return `${[year, month, day].map(formatNumber).join('-')+[hour, minute, second].map(formatNumber).join(':')}`
    } else if (showH_S) {
      return `${[hour, minute, second].map(formatNumber).join(':')}`
    } else {
      return `${[year, month, day].map(formatNumber).join('-')}`
    }
  } else {
    let val = new Date(date * 1000)
    console.log(val)
    const year = val.getFullYear()
    const month = val.getMonth() + 1
    const day = val.getDate()
    const hour = val.getHours()
    console.log(hour)
    const minute = val.getMinutes()
    const second = val.getSeconds()
    if (showhour) {
      return `${[year, month, day].map(formatNumber).join('-')+[hour, minute, second].map(formatNumber).join(':')}`
    } else {
      return `${[year, month, day].map(formatNumber).join('-')}`
    }
  }
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

let testme = (num) => {
  let tmp = [];
  for (var i = 0; i < 1440; i += num) {
    let m = i % 60;
    let h = parseInt(i / 60);
    h = formatZero(h, 2);
    m = formatZero(m, 2);
    tmp.push(h + ":" + m);
  }
  return tmp
}

let formatZero = (num, len) => {
  if (String(num).length > len) return num;
  return (Array(len).join(0) + num).slice(-len);
}

let outTime = (time = '') => {
  time = new Date(1735660799 * 1000).getTime()
  let now_time = new Date().getTime()
  if (getApp().globalData.envVersion == "release") {
    if (now_time > time) {
      return false
    } else {
      return true
    }
  } else {
    return true
  }
}

// 验证身份证
const idcardReg = idcard => {
  const reg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
  if (reg.test(idcard)) {
    // 合法
    return true
  } else {
    return false
  }
}

const caculateTimeago = (dateTimeStamp) => {
  const minute = 1000 * 60; // 把分，时，天，周，半个月，一个月用毫秒表示
  const hour = minute * 60;
  const day = hour * 24;
  const week = day * 7;
  const now = new Date().getTime(); // 获取当前时间毫秒
  const diffValue = now - dateTimeStamp; // 时间差
  let result = '';

  if (diffValue < 0) {
    return;
  }
  const minC = diffValue / minute; // 计算时间差的分，时，天，周，月
  const hourC = diffValue / hour;
  const dayC = diffValue / day;
  const weekC = diffValue / week;
  if (weekC >= 1 && weekC <= 4) {
    result = ` ${parseInt(weekC, 10)}周前`;
  } else if (dayC >= 1 && dayC <= 6) {
    result = ` ${parseInt(dayC, 10)}天前`;
  } else if (hourC >= 1 && hourC <= 23) {
    result = ` ${parseInt(hourC, 10)}小时前`;
  } else if (minC >= 1 && minC <= 59) {
    result = ` ${parseInt(minC, 10)}分钟前`;
  } else if (diffValue >= 0 && diffValue <= minute) {
    result = '刚刚';
  } else {
    const datetime = new Date();
    datetime.setTime(dateTimeStamp);
    const Nyear = datetime.getFullYear();
    const Nmonth = datetime.getMonth() + 1 < 10 ? `0${datetime.getMonth() + 1}` : datetime.getMonth() + 1;
    const Ndate = datetime.getDate() < 10 ? `0${datetime.getDate()}` : datetime.getDate();
    result = `${Nyear}-${Nmonth}-${Ndate}`;
  }
  return result;
}

const verifyMobile = (num) => {
  let phone = /^[1][0-9]{10}$/;
  if (!phone.test(num)) {
    return false
  } else {
    return true
  }
}

const verifyEmail = (num) => {
  let email = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
  if (!email.test(num)) {
    return false
  } else {
    return true
  }
}

const myIsNaN = (value) => {
  return (typeof value === 'number' && !isNaN(value));
}

const setTitle = (title = '超有幸福') => {
  if (wx.getStorageSync('share_partner_name')) {
    wx.setNavigationBarTitle({
      title: wx.getStorageSync('share_partner_name'),
    })
  } else {
    wx.setNavigationBarTitle({
      title: title,
    })
  }
}

const rpxToPx = (v) => {
  let dw = wx.getSystemInfoSync().windowWidth;
  let px = (dw / 750) * Number(v);
  return px
}

const pxToRpx = (v) => {
  let dw = wx.getSystemInfoSync().windowWidth;
  let rpx = (750 / dw) * Number(v);
  return rpx
}

const getSetting = (val) => {
  return new Promise((reslove, reject) => {
    wx.getSetting({
      success: (res) => {
        if (res.authSetting[val] == false) {
          //授权取消
          wx.openSetting();
        } else {
          reslove(res.authSetting[val])
          //授权了或没开启权限
        }
      }
    })
  })
}

// 清除所有空格
const customTrim = (str = '', type = 1) => {
  switch (type) {
    case 1: // strat end
      return str.replace(/(^\s*)|(\s*$)/g, '')
    case 2: // all
      return str.replace(/\s+/g, '')
    case 3: // start
      return str.replace(/(^\s*)/g, '')
    case 4: // end
      return str.replace(/(\s*$)/g, '')
    default:
      return str
  }
}


const is_auth = (is_pay = false) => {
  // if(getApp().globalData.is_show){
  //   return
  // }
  // 判断是否有授权
  let userInfo = wx.getStorageSync('userInfo')
  if (!userInfo.name || userInfo.name == "微信用户") {
    wx.showModal({
      title: '提示',
      content: '请先授权用户信息',
      showCancel: true,
      success: (s) => {
        if (s.confirm) {
          wx.navigateTo({
            url: '/pages/index/get_wx_info',
          })
        }
      }
    })
    return false
  } else {
    if (userInfo.phonenumber == '' || userInfo.phonenumber == 0) {
      if (is_pay) {
        wx.showModal({
          title: '提示',
          content: '请先授权手机号,以便更好的服务',
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/index/login',
              })
            }
          }
        })
        return false
      } else {
        return true
      }
    } else {
      return true
    }
  }

}

let get_device_type = (device_number) => {
  return new Promise((reslove, reject) => {
    getApp().globalData.posts('/index.php/api/app/servicepoints/sorting/ouyoung_api/device_type2', {
      debug: 'tg',
      device_number,
    }).then(res => {
      if (res.data.code == 1) {
        // 设备类型 1 = 咖啡柜 2 = 振兴柜 3 = 洗衣柜
        reslove(res.data.data)
      }
    })
  })
}

let Precedence = () => {
  //判断用户身份
  return new Promise((reslove, reject) => {
    getApp().globalData.post({
      data: {
        do: 'Precedence',
        uid: wx.getStorageSync('userInfo').id,
        a: 'wxapp2'
      }
    }).then(res => {
      let type = res.data.data.type;
      // type:1=用户,2=家政员,3=商家,4=企业,5=个人
      reslove(type)
    })
  })
}

module.exports = {
  formatTime,
  formatNumber,
  caculateTimeago,
  testme,
  outTime,
  idcardReg,
  verifyMobile,
  myIsNaN,
  setTitle,
  verifyEmail,
  is_auth,
  rpxToPx,
  pxToRpx,
  customTrim,
  getSetting,
  get_device_type,
  Precedence
}